﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Tools
{
    public class HttpHelper
    {
        #region Get
        /// <summary>
        /// Get
        /// </summary>
        /// <param name="url"></param>
        /// <param name="Timeout"></param>
        /// <returns></returns>
        public static string Get(string url, int Timeout, out string errMsg)
        {
            string result = "";
            Stream myResponseStream = null;
            StreamReader myStreamReader = null;
            errMsg = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                //request.ContentType = "text/html;charset=UTF-8";
                request.UserAgent = null;
                request.Timeout = Timeout;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                myResponseStream = response.GetResponseStream();
                myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                result = myStreamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                LogHelper.WriteErrorLog("HttpHelp.HttpGet异常", ex);
            }
            finally
            {
                if (myStreamReader != null)
                    myStreamReader.Close();

                if (myResponseStream != null)
                    myResponseStream.Close();

            }
            return result;
        } 
        #endregion

        #region Post
        /// <summary>
        /// Post
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="json"></param>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public static string Post(Dictionary<string, string> headers, string json, string url, out string errMsg, int timeout = 1000)
        {
            System.GC.Collect();//垃圾回收，回收没有正常关闭的http连接
            string result = "";//返回结果
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream reqStream = null;
            errMsg = "";
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式 
                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Timeout = timeout * 1000;
                #region 设置报文头
                foreach (var item in headers)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
                #endregion

                //设置POST的数据类型和长度
                request.ContentType = "application/json";
                byte[] data = System.Text.Encoding.UTF8.GetBytes(json);
                request.ContentLength = data.Length;
                //往服务器写入数据
                reqStream = request.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();

                //获取服务端返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (Exception ex)
            {
                result = "";
                errMsg = ex.Message;
                LogHelper.WriteErrorLog("HttpHelper.Post发生异常,异常信息：" + ex.Message, ex);
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        } 
        #endregion
    }
}
